﻿using System;
using System.Linq;
using System.Reflection;
using System.Transactions;
using Yto.Repositories;

namespace Yto.Unitwork
{
    [AttributeUsage(AttributeTargets.Method)]
    public class UnitworkAttribute : Attribute
    {
        public TransactionScopeOption? Scope;

        public bool? IsTransactional;

        public bool IsDisposed;

        public UnitworkAttribute()
        {
        }

        public UnitworkAttribute(TransactionScopeOption scope)
        {
            IsTransactional = true;
            Scope = scope;
        }

        internal static UnitworkAttribute GetAttributeByMethodTarget(MemberInfo memberInfo)
        {
            //var attributes = Attribute.GetCustomAttributes(memberInfo, typeof(UnitworkAttribute), true)
            //    .Cast<UnitworkAttribute>().ToArray();
            var attributes = memberInfo.GetCustomAttributes(typeof(UnitworkAttribute), true)
                .Cast<UnitworkAttribute>()
                .ToArray();
            if (attributes.Length > 0)
            {
                return attributes[0];
            }
            if (typeof(IBaseRepository).IsAssignableFrom(memberInfo.DeclaringType))
            {
                return new UnitworkAttribute();
            }

            return null;
        }
    }
}
